<?php

// +---------------------------------------------+
// |     Copyright  2010 - 2018 InterPhoto       |
// |     http://www.weentech.com                 |
// |     This file may not be redistributed.     |
// +---------------------------------------------+

include('includes/Admin.Core.php');

CheckAccess('manageimage');


PrintHeader('批量添加图片');

$action = ForceIncomingString('action', 'displaydefault');

$uploaddir = BASEPATH.'MyWebsiteImages/';
$ImageFromPath = BASEPATH . 'UploadImages/';

@set_time_limit(0);

// ############################## FUNCTIONS #############################

function CreateDirectory($path) {
	if (!file_exists($path)) {
		mkdir($path, 0777);
		@chmod($path, 0777);
	}
}

function CreateImageFile($src_path, $des_path, $new_dims) {
	$source = @imagecreatefromjpeg($src_path);

	if ($source) {
		$imageX = @imagesx($source);
		$imageY = @imagesy($source);
		
		if ($imageX >= $imageY) {
			if($imageX >= $new_dims){
				$thumbX = $new_dims;
				$thumbY = (int)(($thumbX*$imageY) / $imageX );
			}else{
				$thumbX = $imageX;
				$thumbY = $imageY;
			}
		} else {
			if($imageY >= $new_dims){
				$thumbY = $new_dims;
				$thumbX = (int)(($thumbY*$imageX) / $imageY );
			}else{
				$thumbX = $imageX;
				$thumbY = $imageY;
			}
		}

		$dest_thum  = @imagecreatetruecolor($thumbX, $thumbY);
		@imagecopyresampled ($dest_thum, $source, 0, 0, 0, 0, $thumbX, $thumbY, $imageX, $imageY);
		@imageinterlace($dest_thum);
		@imagejpeg($dest_thum,$des_path,85);
		@ImageDestroy($dest_thum);
		@ImageDestroy($source);
	}
}


function GetCategorySelect($selectname, $selectedid = 0){
	$sReturn = '<select name="' . $selectname . '">';
	$sReturn .= GetOptions($selectedid);
	$sReturn .= '</select>';

	return $sReturn;
}

function GetOptions($selectedid = 0, $parentid = 0, $sublevelmarker = ''){
	global $icategories;

	if($parentid) $sublevelmarker .= '&minus;&minus;';

	$allicategories = $icategories;
	foreach($allicategories as $value){
		if($parentid == $value['parentid']){
			$sReturn .= '<option value="' . $value['categoryid'] . '" ' . Iif($selectedid == $value['categoryid'], 'SELECTED', '') . '>' . $sublevelmarker . $value['title'] . '</option>';

			$sReturn .= GetOptions($selectedid, $value['categoryid'], $sublevelmarker);
		}
	}

	return $sReturn;
}


// ################################ IN IMAGES ################################

if($action == 'in')
{
	$categoryid     = ForceIncomingInt('c');
	$usergroup        = ForceIncomingString('ug');
	$usergroupids     = Iif(IsGet('ugs'),urldecode(ForceIncomingString('ugs')), ForceIncomingArray('ugs'));
	$username        = Iif(IsGet('un'),urldecode(ForceIncomingString('un')), ForceIncomingString('un'));
	$watermark     = ForceIncomingInt('w');
	$actived     = ForceIncomingInt('a');
	$number     = ForceIncomingInt('n', 1);

	if(IsPost('ug')){
		if($usergroup == 'all' OR count($usergroupids) < 1){
			$usergroupids = 'all';
		}else{
			$usergroupids = '('.implode(');(', $usergroupids).')';
		}
	}


	if (!$categoryid)
	{
		$errors[] ='上传图片前请先添加图片分类目录!';
	}

	if (!function_exists('imagecreatetruecolor'))
	{
		$errors[] ='服务器PHP环境不支持GD2库, 无法上传图片文件!';
	}

	if (!is_dir($uploaddir)){
		$errors[] ='保存图片的文件夹: MyWebsiteImages/ 不存在!';
	}else if (!is_writable($uploaddir)){
		$errors[] = '保存图片的文件夹: MyWebsiteImages/ 不可写! - 文件夹属性需改为: 0777';
	}

	if(!isset($errors))	{

		PrintSection('批量添加图片');
        echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
		<tr>
		<td class="tdrow3"></br />
		系统正在处理第 <font class=ohblueb>' . $number . '</font> 个图片, 请耐心等待......<br /><br />
		</td>
		</tr>
        </table>';
        EndSection();

		echo '<script type="text/javascript">window.location="admin.ftpimages.php?action=do&c='.$categoryid.'&un='.urlencode($username).'&w='.$watermark.'&a='.$actived.'&n='.$number.'&ugs='.urlencode($usergroupids).'"</script>';

	}else{
		PrintErrors($errors, '批量添加图片错误');
		$action = 'displaydefault';
	}

}

// ################################ DO INSERT IMAGES #############################

if($action == 'do')
{
	$categoryid     = ForceIncomingInt('c');
	$usergroupids     = urldecode(ForceIncomingString('ugs'));
	$username        = urldecode(ForceIncomingString('un'));
	$watermark     = ForceIncomingInt('w');
	$actived     = ForceIncomingInt('a');
	$number     = ForceIncomingInt('n');

	$FolderHandle = @opendir($ImageFromPath);

	while (false !== ($Item = readdir($FolderHandle))) {
		if ($imagesize = @getimagesize($ImageFromPath.$Item) AND $imagesize[2] == '2' AND strtolower(substr($Item, -4)) == '.jpg') {

			$file_path_name = DisplayDate(time(), 'Y_m');
			$imagename = md5(uniqid(COOKIE_KEY.time())).'.jpg';
			$copysuccess = true;

			$file_path = $file_path_name.'_'.WEBSITE_KEY;

			CreateDirectory($uploaddir.$file_path);
			CreateDirectory($uploaddir.$file_path.'/32x32/');
			CreateDirectory($uploaddir.$file_path.'/80x80/');
			CreateDirectory($uploaddir.$file_path.'/160x160/');
			CreateDirectory($uploaddir.$file_path.'/760x760/');
			CreateDirectory($uploaddir.$file_path.'/original/');

			if ($imagesize[0] > 760 || $imagesize[1] > 760) {
				if (@rename($ImageFromPath.$Item, $uploaddir.$file_path.'/original/'.$imagename)) {
					CreateImageFile($uploaddir.$file_path.'/original/'.$imagename, $uploaddir.$file_path."/760x760/".$imagename,'760');
					CreateImageFile($uploaddir.$file_path.'/760x760/'.$imagename, $uploaddir.$file_path."/160x160/".$imagename,'160');
					CreateImageFile($uploaddir.$file_path.'/160x160/'.$imagename, $uploaddir.$file_path."/80x80/".$imagename,'80');
					CreateImageFile($uploaddir.$file_path.'/80x80/'.$imagename, $uploaddir.$file_path."/32x32/".$imagename,'32');
				}else{
					$copysuccess = false;
				}
			}else{
				if (@rename($ImageFromPath.$Item, $uploaddir.$file_path.'/760x760/'.$imagename)) {
					CreateImageFile($uploaddir.$file_path.'/760x760/'.$imagename, $uploaddir.$file_path."/160x160/".$imagename,'160');
					CreateImageFile($uploaddir.$file_path.'/160x160/'.$imagename, $uploaddir.$file_path."/80x80/".$imagename,'80');
					CreateImageFile($uploaddir.$file_path.'/80x80/'.$imagename, $uploaddir.$file_path."/32x32/".$imagename,'32');
				}else{
					$copysuccess = false;
				}
			}

			if($copysuccess){
				$DB->query("INSERT INTO " . TABLE_PREFIX . "images VALUES (NULL, '$ordernum',  '$categoryid', '$userinfo[userid]', '$username', '$actived', '$watermark', '$sale', 0, '$usergroupids', '$file_path_name', '$imagename', '$price', '".str_replace(array('"', '\''), '', iconv('gbk','utf-8',$Item))."', '$description', '', '$keywords', '$url', '0', '0', '".time()."')");

				$imageid = $DB->insert_id();
				$DB->query("UPDATE " . TABLE_PREFIX . "images SET ordernum = '$imageid' WHERE imageid = '$imageid'");

				$number++;
			}

			PrintRedirect('admin.ftpimages.php?action=in&c='.$categoryid.'&un='.urlencode($username).'&w='.$watermark.'&a='.$actived.'&n='.$number.'&ugs='.urlencode($usergroupids), 0);

			exit();

		}
	}

	@closedir($ImageFromPath);

	PrintSection('批量添加图片结果');
	echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
	<tr>
	<td class="tdrow3"></br />
	批量添加图片操作完成! 共计添加: <font class=ohblueb>' . ($number -1) . '</font> 个图片.<br /><br />
	</td>
	</tr>
	</table>';
	EndSection();

	$action = 'displaydefault';
}


// ############################ DISPLAY IMAGE FORUM #############################

if($action == 'displaydefault')
{
	$getcategories = $DB->query("SELECT categoryid, parentid, title  FROM " . TABLE_PREFIX . "categories ORDER BY ordernum");
	$icategories = $DB->getrows($getcategories);

	@chmod($uploaddir, 0777);

	$ftpEnabled = false;

	if (!is_dir($ImageFromPath)) {
		$errors ='批量上传文件夹 (UploadImages/) 不存在!';
	}else{
		@chmod($ImageFromPath, 0777);
		if (!is_writable($ImageFromPath))	$errors = '批量上传文件夹 (UploadImages/) 不可写! - 属性需改为: 0777';
	}

	if (isset($errors)){
		PrintErrors($errors, '初始化错误');
	}else{
		$ftpEnabled = true;
	}

	$FolderHandle = @opendir($ImageFromPath);
	$filecount = 0;
	$jpgfilecount = 0;

	while (false !== ($Item = readdir($FolderHandle))) {
		if ($Item != '.' 	&& $Item != '..') {
			$filecount++;

			if ($imagesize = @getimagesize($ImageFromPath.$Item) AND $imagesize[2] == '2' AND strtolower(substr($Item, -4)) == '.jpg') {
				$jpgfilecount++;
			}
		}
	}

	@closedir($ImageFromPath);

	PrintSection('操作说明');

	echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
	<tr>
	<td class="tdrow2" width="120"><b>批量添加说明:</b></td>
	<td class="tdrow3">1). 建议先在本地使用Photoshop等工具处理<font class=ohredb>JPG</font>图片, 文件太大将占用更多的网站空间, 并影响批量添加速度.<BR>2). 用FTP工具将多个图片文件上传到网站的 <font class=ohblueb>/UploadImages/</font> 目录下.<BR>3). 仅允许添加<font class=ohredb>JPG</font>类型的图片文件, 其它类型的文件无效. 添加成功后, 上传的原始图片将自动删除.</td>
	</tr>
	<tr>
	<td class="tdrow2" width="120"><b>当前状态:</b></td>
	<td class="tdrow3">当前UploadImages目录下共有文件 <b>'.$filecount.'</b> 个, 可用JPG文件 <font class=ohblueb>'.$jpgfilecount.'</font> 个.</td>
	</tr>
	</table>';

	EndSection();

	$getusergroups = $DB->query("SELECT groupid, name FROM " . TABLE_PREFIX . "usergroups ORDER BY groupid");
	while($usergroup = $DB->getrow($getusergroups)) {
		$usergroups[$usergroup['groupid']] = $usergroup['name'];
	}


	PrintSection('批量图片设置');

	echo '<form method="post" action="admin.ftpimages.php">
	<input type="hidden" name="action" value="in" />
	<table width="100%" border="0" cellpadding="5" cellspacing="0">
	<tr>
	<td class="tdrow2" width="120"><b>所属目录:</b></td>
	<td class="tdrow3">'.GetCategorySelect('c').'</td>
	</tr>
	<tr>
	<td class="tdrow2" width="120"><b>可见用户组:</b></td>
	<td class="tdrow3"><input type="radio" name="ug" value="all" checked="checked" onclick="HideDIV(\'div_usergroupids\');">所有用户组&nbsp;&nbsp;&nbsp;<input type="radio" name="ug" value="none" onclick="ShowDIV(\'div_usergroupids\');">选择用户组 (注: 指此图片对于哪些用户组可见)<BR><div id="div_usergroupids" style="border: 1px solid #996600;background-color:#fffeec;margin:6px;padding:6px; display: none;">';

	foreach($usergroups as $key => $value)
	{
		echo '<input  type="checkbox" name="ugs[]" value="' . $key . '">' . $value . '&nbsp;&nbsp;&nbsp;&nbsp;';
	}

	echo '</div>
	</td>
	</tr>
	<tr>
	<td class="tdrow2" width="120"><b>发布人:</b></td>
	<td class="tdrow3"><input type="text" name="un" value="'.$userinfo['username'].'" size="16" /></td>
	</tr>
	<tr>
	<td class="tdrow2" width="120"><b>添加水印:</b></td>
	<td class="tdrow3"><input type="checkbox" name="w" value="1" CHECKED> <b>是:</b> 是否在显示大图时自动添加水印?</td>
	</tr>
	<tr>
	<td class="tdrow2" width="120"><b>是否发布:</b></td>
	<td class="tdrow3"><input type="checkbox" name="a" value="1" CHECKED> <b>是:</b> 是否发布这些图片?</td>
	</tr>
	<tr>
	<td class="tdrow1" bgcolor="#FCFCFC" colspan="2" align="center">
	<input type="submit" value=" 批量添加 " ' . Iif($ftpEnabled, '', 'disabled') . ' />
	</td>
	</tr>
	</table>
	</form>';

	EndSection();
}

// ############################### PRINT FOOTER ################################

PrintFooter();

?>